<?php



namespace App\Services\Business\Services;

use App\Services\Business\Interfaces\CommentServiceInterface;
use App\Services\Business\Models\Comment;
use Illuminate\Support\Facades\Auth;
class CommentService implements CommentServiceInterface
{

    /**
     * @param int $resource_id
     * @return array
     */
    public function comments(int $resource_id,string $resource_type): array
    {
        $comments = Comment::query()->whereResourceId($resource_id)->whereResourceType($resource_type)->orderByDesc('id')->limit(200)->get()->toArray();

        return $comments;
    }

    /**
     * @param int $resourceId
     * @param string $originalContent
     *
     * @return array
     */
    public function create($type,$id, $data): array
    {

        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $count=0;
        if($data['parent_id']!= 0 && $data['reply_id']===0){
            $record =  Comment::query()->find($data['parent_id']);
            $record->increment('children_count');

        }
        $comment = new Comment([
            'user_id' => Auth::id(),
            'children_count'=>$count,
            'parent_id'=>$data['parent_id']??0,
            'reply_id'=>$data['reply_id'],
            'content' =>$data['content']??''
        ]);

        $resource->increment('comments_count',1);
        $resource->comments()->save($comment);

        return $comment->toArray();
    }

    /**
     * @param int $id
     * @return array
     */
    public function find(int $id): array
    {
        return Comment::findOrFail($id)->toArray();
    }
}
